/*
 * pi.c - Calculates π
 */

#include <math.h>

/*
 *              k
 *       ∞  (-1)     ⎛1   1   1   1   1  ⎞
 * π = 4 ∑  –––– = 4 ⎜– - — + – - – + – …⎟
 *      k=0 2k+1     ⎝1   3   5   7   9  ⎠
 *
 */
double
pi_series(long n)
{
	double sum = 0.0;
	long i;
	for (i = 0; i < n; i++)
		sum += pow(-1.0, i) / (2.0*i + 1);
	return 4.0 * sum;
}

double
pi_gauss_legendre(double precision)
{
	double a = 1.0;
	double b = 1/sqrt(2);
	double t = 1.0/4.0;
	double p = 1.0;
	double a1, b1, t1, p1;
	while ((a-b) > precision) {
		a1 = (a + b) / 2.0;
		b1 = sqrt(a*b);
		t1 = t - p*pow(a-a1, 2);
		p1 = 2*p;
		a = a1;
		b = b1;
		t = t1;
		p = p1;
	}
	return pow(a + b, 2) / (4.0 * t);
}
